<?php

namespace app\api\controller;

use app\admin\model\wanlshop\PayIntegral;
use app\common\controller\Api;
use tidy;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $params = $this->request->param();
        \think\Log::error("testAPI");
        \think\Log::error($params);
        $params['json'] = json_encode($params);
        if (!request()->param('invoice_no')) {
            $this->error('invoice_no未成功获取');
        }
        if (!\app\admin\model\Tickets::where('invoice_no', request()->param('invoice_no'))->find()) {
            $this->model = new \app\admin\model\Tickets;
            $result = $this->model->allowField(true)->save($params);
        }else{
            $result = \app\admin\model\Tickets::where('invoice_no', request()->param('invoice_no'))->find();
        }

        $company = \app\admin\model\Company::where('name', request()->param('heating_company'))->find();
        if ($company && $company['switch'] && $company['appid'] && $company['secret']) {
            $config = [
                'app_id'    => $company['appid'] ?? '',
                'secret'        => $company['secret'] ?? '',
                'response_type' => 'array'
            ];
            $app = \EasyWeChat\Factory::officialAccount($config);
            $proportion  = $this->proportion($result);
            if($proportion>0){
                $url = 'https://c.hrbyuecai.com/tuangou/#/pages/user?integral=1&ticket_id='.$result['id'];
            }else{
                $url = 'https://c.hrbyuecai.com/tuangou/#';
            }

            $new_params = [
                'touser' => $params['openid'] ?? 'o8onm0jRa3oKKFFyM-UmEbU8OPLs',
                'template_id' => $company['template_id'] ?: 'lwzP1ei696Ru7o5im04fPcpMjdHndg76cLLK_DDoDuc',
                'appid' => $wxMiniProgram['app_id'] ?? 'wxd9486d8ee29b1ee9',
                 'url' =>$url,
                // 'miniprogram' => [
                //     'appid' => $wxMiniProgram['app_id'],
                //     'pagepath' => 'pages/myCourse/myCourse',
                // ],
                'data' => [
                    'thing6' => ["value" => $params['name'] ?? '测试订单'],
                    'time5' => ["value" => date('Y-m-d H:i:s', time())],
                ],
            ];
            $res = $app->template_message->send($new_params);
            if ($res && !isset($res['errcode'])) {
                \app\admin\model\Tickets::where('invoice_no', request()->param('invoice_no'))->update([
                    'notice_time' => time()
                ]);
            }
            // var_dump($res);
        }
        $this->success('ok', $params);
    }
    public function proportion($ticket)
    {
        $proportion = 0;
        //获取添加积分比例
        $dataList = PayIntegral::select();
        foreach ($dataList as $data) {
            // 检查 pay_annual 是否与 year 匹配
            if ($ticket['pay_annual'] == $data['year']) {
                // 将 date 类型的 time 转换为时间戳 (假设 $data['time'] 是 Y-m-d 格式)
                $dataTime = strtotime($data['time']);
                // 检查 payment_time 是否小于 dataTime
                if ($ticket['payment_time'] < $dataTime) {
                    // 返回符合条件的 proportion
                    return $data['proportion'];
                }
            }
        }
        return $proportion;
    }
    //把请求发送到微信服务器换取二维码
    public static function httpRequest($url, $data = '', $method = 'GET')
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        try {
            curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        } catch (\Throwable $th) {
            //throw $th;
        }
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if ($method == 'POST') {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '') {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    public function seesee(){

        $config = get_addon_config('wanlshop');
       $url =  $config['h5']['domain'].($config['h5']['router_mode'] == 'hash' ? '/#':'') . '/pages/page/success?type=pay';
       halt($url);
    }
}
